<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="消费类型" prop="selectedProducts">
        <el-tree-select
          v-model="formData.selectedProducts"
          :data="productSortTree"
          :props="defaultProps"
          node-key="id"
          multiple
          show-checkbox
          check-strictly
          default-expand-all
          placeholder="请选择消费类型"
          value-key="id"
          style="width: 100%"
          @check="handleProductSelectionChange"
        />
      </el-form-item>

      <el-form-item label="交易渠道" prop="transactionChannel">
        <el-select v-model="formData.transactionChannel" placeholder="请选择交易渠道" style="width: 100%;">
          <el-option
            v-for="channel in transactionChannelOptions"
            :key="channel.value"
            :label="channel.label"
            :value="channel.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="折扣率" prop="discount">
        <el-input-number
          v-model="formData.discount"
          :min="0.01"
          :max="1"
          :precision="2"
          :step="0.1"
          placeholder="请输入折扣率"
          style="width: 100%;"
          @change="calculateDiscountedAmount"
        />
        <div class="el-form-item-msg">0.1-1之间的小数，如0.8表示8折，1表示不打折</div>
      </el-form-item>

      <el-form-item label="消费金额(元)" prop="amount">
        <el-input-number
          v-model="formData.amount"
          :min="0"
          :precision="2"
          :step="1"
          placeholder="请输入消费金额"
          style="width: 100%;"
          disabled
        />
        <template v-if="formData.discount < 1 && formData.originalAmount > 0">
          <div class="el-form-item-msg">原价: {{ formatYuan(formData.originalAmount) }}元，折后价: {{ formatYuan(formData.amount) }}元，优惠: {{ formatYuan(formData.originalAmount - formData.amount) }}元</div>
        </template>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {FinancialFlow, FinancialFlowApi} from '@/api/javainfo/financialflow'
import {Pet} from '@/api/javainfo/pet'
import * as ProductSortApi from '@/api/javainfo/product-sort'
import {defaultProps, handleTree} from '@/utils/tree'

/** 宠物消费 弹窗 */
defineOptions({ name: 'PetConsumptionDialog' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('宠物消费') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中

// 用户ID和宠物信息
const userId = ref<number>()
const pet = ref<Pet>()

// 商品分类树形结构
const productSortTree = ref<Tree[]>([])

const formData = ref({
  selectedProducts: [] as number[], // 选中的商品分类ID
  transactionChannel: 'ALIPAY', // 默认支付宝
  discount: 1, // 默认不打折
  amount: 0, // 消费金额（元）
  originalAmount: 0, // 原始金额（未打折）
  remark: '', // 备注
})

/** 格式化价格（分转元） */
const formatPrice = (price: number) => {
  if (price === undefined || price === null) return '¥0.00'
  return '¥' + (price / 100).toFixed(2)
}

/** 格式化元为字符串 */
const formatYuan = (yuan: number) => {
  return yuan.toFixed(2)
}

// 交易渠道选项
const transactionChannelOptions = [
  { value: 'ALIPAY', label: '支付宝' },
  { value: 'WECHAT', label: '微信' },
  { value: 'BANK', label: '网商银行' },
  { value: 'BALANCE', label: '现金' },
  { value: 'SYSTEM', label: '系统' }
]

const formRules = reactive({
  selectedProducts: [{ required: true, message: '消费类型不能为空', trigger: 'change' }],
  transactionChannel: [{ required: true, message: '交易渠道不能为空', trigger: 'change' }],
  discount: [
    { required: true, message: '折扣率不能为空', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 1, message: '折扣率必须在0.01-1之间', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '消费金额不能为空', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '消费金额必须大于0', trigger: 'blur' }
  ],
})

const formRef = ref() // 表单 Ref

/** 计算折扣后金额 */
const calculateDiscountedAmount = () => {
  if (formData.value.originalAmount > 0) {
    // 应用折扣率，保留两位小数
    formData.value.amount = parseFloat((formData.value.originalAmount * formData.value.discount).toFixed(2))
  }
}

/** 处理商品分类选择变化 */
const handleProductSelectionChange = (currentNode: any, info: any) => {
  // 获取当前选中的所有节点ID
  const selectedIds = info.checkedKeys || formData.value.selectedProducts || []

  console.log('选中的节点ID:', selectedIds)

  // 计算选中商品的总金额
  let totalAmount = 0
  selectedIds.forEach((id: number) => {
    // 在树形结构中查找选中的节点
    const product = findNodeById(productSortTree.value, id)
    console.log(`节点 ${id}:`, product)
    if (product && product.price) {
      totalAmount += product.price / 100 // 价格从分转换为元
      console.log(`节点 ${id} 价格:`, product.price / 100)
    }
  })

  // 保存原始金额
  formData.value.originalAmount = parseFloat(totalAmount.toFixed(2))

  // 应用折扣率
  calculateDiscountedAmount()

  console.log('原始金额:', formData.value.originalAmount)
  console.log('折扣后金额:', formData.value.amount)
}

/** 在树形结构中根据ID查找节点 */
const findNodeById = (nodes: Tree[], id: number): Tree | null => {
  for (const node of nodes) {
    if (node.id === id) {
      return node
    }
    if (node.children && node.children.length > 0) {
      const found = findNodeById(node.children, id)
      if (found) {
        return found
      }
    }
  }
  return null
}

/** 生成订单号 */
const generateOrderNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  const second = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')

  return `CF${year}${month}${day}${hour}${minute}${second}${random}`
}

/** 获取商品分类树 */
const getProductSortTree = async () => {
  try {
    const data = await ProductSortApi.getSimpleProductSortList()
    console.log('获取到的商品分类数据:', data)
    // 构造树形结构
    productSortTree.value = []
    const treeData: Tree = { id: 0, name: '顶级分类', children: [] }
    treeData.children = handleTree(data)
    productSortTree.value.push(treeData)
    console.log('构造的树形结构:', productSortTree.value)
  } catch (error) {
    console.error('获取商品分类树失败', error)
    message.error('获取商品分类树失败')
  }
}

/** 打开弹窗 */
const open = async (uid: number, p: Pet) => {
  dialogVisible.value = true
  userId.value = uid
  pet.value = p
  dialogTitle.value = `为 ${p.petName} 消费`
  resetForm()

  // 获取商品分类树
  await getProductSortTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 提交请求
  formLoading.value = true
  try {
    // 构建财务流水数据
    const data: FinancialFlow = {
      flowId: undefined, // 新增时不需要ID
      userId: userId.value,
      petId: pet.value?.id,
      orderNumber: generateOrderNumber(), // 生成订单号
      amountType: 'CONSUME', // 消费类型
      transactionChannel: formData.value.transactionChannel,
      amount: Math.round(formData.value.amount * 100), // 转换为分
      balanceAfter: undefined, // 后端计算
      businessType: 'PRODUCT_CONSUME', // 商品消费类型
      relatedId: undefined, // 消费没有关联业务ID
      remark: formData.value.remark || `为 ${pet.value?.petName} 消费`,
      discount: formData.value.discount, // 折扣率
    }

    // 调用API保存数据
    await FinancialFlowApi.createFinancialFlow(data)
    message.success('消费记录添加成功')
    dialogVisible.value = false

    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    selectedProducts: [],
    transactionChannel: 'ALIPAY',
    discount: 1,
    amount: 0,
    originalAmount: 0,
    remark: '',
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.el-form-item-msg {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>

